package com.xcap.security.datasourceauthentication.config;

import com.xcap.security.datasourceauthentication.filter.ValidateFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * 安全配置类
 */

@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true)  //启用全局方法控制
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private ValidateFilter validateFilter;

    @Resource
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    //安全加密器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public  void configure(HttpSecurity http) throws Exception {
        //配置登录登录之前添加一共验证码的过滤器
        http.addFilterBefore(validateFilter, UsernamePasswordAuthenticationFilter.class);
        //所有的请求，都需要认证
        http.authorizeRequests()
                .mvcMatchers("/code/image")
                .permitAll()//放开验证码的请求
                .anyRequest().authenticated();
        http.formLogin()
                .loginPage("/toLogin")   //配置登录界面
                .usernameParameter("uname")  //用户参数名字
                .passwordParameter("pwd")  //密码
                .loginProcessingUrl("/login/doLogin")  //单击登录后进入url
                .failureForwardUrl("/toLogin")  //登录失败
                .successForwardUrl("/index/toIndex")  //登录成功
                .successHandler(myAuthenticationSuccessHandler) //token认证成功处理器
                .permitAll();

        http.logout().logoutSuccessUrl("/toLogin");
        //防止前端黑客攻击，token  但是我们这边没有用到
        http.csrf().disable();//关闭跨域请求保护
    }

}
